<?php
namespace app\massage\controller;
use app\ApiRest;

use app\card\model\UserPhone;
use app\card\model\UserSk;
use app\massage\model\CarAtvList;
use app\massage\model\CarAtvRecord;
use app\massage\model\CarDriver;
use app\massage\model\CarGame;
use app\massage\model\CarLineUp;
use app\massage\model\CarType;
use app\massage\model\CarUserTrophy;
use app\massage\model\Coach;
use app\massage\model\CoachCollect;
use app\massage\model\Commission;
use app\massage\model\Config;
use app\massage\model\CouponAtv;
use app\massage\model\CouponAtvRecord;
use app\massage\model\CouponAtvRecordCoupon;
use app\massage\model\CouponAtvRecordList;
use app\massage\model\CouponRecord;
use app\massage\model\Address;

use app\massage\model\Order;
use app\massage\model\RefundOrder;
use app\massage\model\SynMember;
use app\massage\model\User;
use app\member\model\Level;
use app\shop\model\DistributionList;
use app\shop\model\Integral;
use think\App;
use think\facade\Db;
use think\Request;


class IndexUser extends ApiRest
{

    protected $model;

    protected $address_model;

    protected $record_model;

    protected $coupon_record_model;

    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new User();

        $this->address_model = new Address();

        $this->record_model = new CarAtvRecord();

        $this->coupon_record_model = new CouponRecord();
        //积分到账
        point_success($this->_uniacid);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-16 15:41
     * @功能说明:用户报名列表
     */
    public function userAtvRecord(){

        $atv_model = new CarAtvList();

        $atv_model->initAtv();

//        $this->record_model->autoCancelRecord($this->getUserId());

        $input = $this->_param;

        $dis[] = ['a.user_id','=',$this->getUserId()];
        //去除没有取消的
//        $dis[] = ['a.status','>',-1];

        if(!empty($input['status'])){

            $dis[] = ['b.atv_status','=',$input['status']];
        }

        if(!empty($input['start_time'])){

            $dis[] = ['b.atv_s_time','between',"{$input['start_time']},{$input['end_time']}"];
        }

        if(!empty($input['record_status'])){

            $dis[] = ['a.pay_type','=',7];
        }

        $data = $this->record_model->atvRecordList($dis);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$vs){

                $vs['day_text'] = date('Y.m.d',$vs['start_time']).' - '.date('Y.m.d',$vs['end_time']);

            }

        }

        return $this->success($data);
    }






    /**
     * @author chenniang
     * @DataTime: 2021-09-16 15:46
     * @功能说明:报名详情
     */
    public function recordInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data['record_info'] = $this->record_model->dataInfo($dis);

        $data['record_info']['create_time'] = date('Y-m-d H:i:s',$data['record_info']['create_time']);

        $data['record_info']['hx_time'] = date('Y-m-d H:i:s',$data['record_info']['hx_time']);

        $atv_model = new CarAtvList();

        $data['atv_info'] = $atv_model->dataInfo(['id'=>$data['record_info']['atv_id']]);

        $data['game_info']['top'] = $this->record_model->getRecordTop($data['record_info']);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-10-20 09:54
     * @功能说明:不支付就调用这个状态
     */
    public function payCancelRecord(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $record_info = $this->record_model->dataInfo($dis);

        $res = $this->record_model->cancelRecord($record_info,2);

        return $this->success($res);

    }
    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:48
     * @功能说明:个人中心
     */
    public function index(){

        $data = $this->getUserInfo();

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['status','in',[1,2,3,4]];

        $driver_model = new CarDriver();
        //查看是否是团长
        $cap_info = $driver_model->dataInfo($cap_dis);
        //-1表示未申请团长，1申请中，2已通过，3取消,4拒绝
        $data['driver_status'] = !empty($cap_info)?$cap_info['status']:-1;

        $data['sh_text'] = !empty($cap_info)?$cap_info['sh_text']:'';
        //优惠券数
        $data['coupon_count'] = $this->coupon_record_model->couponCount($this->getUserId());

        $data['balance'] = $this->model->where(['id'=>$this->getUserId()])->sum('balance');

        $data['integral']= $this->model->where(['id'=>$this->getUserId()])->sum('integral');

        $member_level = $this->model->where(['id'=>$this->getUserId()])->value('member_level');

        $data['balance'] = round($data['balance'] ,2);
        //查看荣誉杯
        $user_trophy_model = new CarUserTrophy();

        $data['user_trophy'] = $user_trophy_model->userTrophy($this->getUserId());

        $level_model = new Level();

        $data['member_level_info'] = $level_model->levelInfo(['id'=>$member_level]);

        return $this->success($data);

    }




    /**
     * @author chenniang
     * @DataTime: 2021-09-27 10:08
     * @功能说明:取消预约
     */
    public function cancelAtvRecord(){

        $input = $this->_input;

        $record = $this->record_model->dataInfo(['id'=>$input['record_id']]);

        if(!in_array($record['pay_type'],[1,2])){

            $this->errorMsg('状态错误');
        }

        if($record['end_time']<time()){

            $this->errorMsg('活动已经结束');
        }

        Db::startTrans();

        $res = $this->record_model->cancelRecord($record);

        if(!empty($res['code'])){

            Db::rollback();

            $this->errorMsg($res['msg']);
        }

        //已经支付 需要退款
        if($record['pay_type']>1&&$record['pay_price']>0){
            //微信支付
            if($record['balance']<=0){
                //微信退款
                $response = orderRefundApi($this->payConfig(),$record['pay_price'],$record['pay_price'],$record['transaction_id']);
                //如果退款成功修改一下状态
                if ( isset( $response[ 'return_code' ] ) && isset( $response[ 'result_code' ] ) && $response[ 'return_code' ] == 'SUCCESS' && $response[ 'result_code' ] == 'SUCCESS' ) {

                    $response['out_refund_no'] = !empty($response['out_refund_no'])?$response['out_refund_no']:$record['order_code'];

                    $this->record_model->dataUpdate(['id'=>$record['id']],['refund_code'=>$response['out_refund_no']]);

                }else {

                    //失败就报错
                    $discption = !empty($response['err_code_des'])?$response['err_code_des']:$response['return_msg'];

                    Db::rollback();

                    return ['code'=>500,'msg'=> $discption];

                }
            }else{

                //余额
                $user_model = new User();

                $user = $user_model->dataInfo(['id'=>$record['user_id']]);

                $balance = $user['balance'] + $record['pay_price'];

                $res = $user_model->dataUpdate(['id'=>$record['user_id'],'balance'=> $user['balance']],['balance'=>$balance]);

                if($res==0){

                    Db::rollback();

                    $this->errorMsg('退款失败');
                }

            }

        }

        Db::commit();

        return $this->success($res);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-27 13:45
     * @功能说明:活动预约核销码
     */
    public function atvRecordQr(){

        $input = $this->_input;

        $key = 'atv_app_qr'.$input['record_id'];

        $qr  = getCache($key,$this->_uniacid);

        if(empty($qr)){
            //获取二维码
            $qr = $this->model->orderQr($input,$this->_uniacid);

            setCache($key,$qr,86400,$this->_uniacid);
        }

        return $this->success($qr);


    }




    /**
     * @author chenniang
     * @DataTime: 2021-09-27 13:44
     * @功能说明:核销活动预约
     */
    public function hxAtvRecord(){

        $input = $this->_input;

        $record = $this->record_model->dataInfo(['id'=>$input['record_id']]);

        if($record['pay_type']!=3){

            $this->errorMsg('报名状态错误');

        }

        $user_role = $this->model->where(['id'=>$this->getUserId()])->value('role');

        if($user_role!=1){

            $this->errorMsg('管理员才有核销权限');
        }

        $config_model = new Config();

        $config = $config_model->dataInfo(['uniacid'=>$record['uniacid']]);

        $atv_model = new CarAtvList();

        $integral_time = $atv_model->where(['id'=>$record['atv_id']])->value('integral_time');

        Db::startTrans();

        $update = [

            'hx_user' => $this->getUserId(),

            'pay_type'=> 7,

            'hx_time' => time(),
            //可申请退款的时间
            'can_refund_time'=> time()+$integral_time*3600

        ];

        $res = $this->record_model->dataUpdate(['id'=>$input['record_id']],$update);

        if($res==0){

            Db::rollback();

            $this->errorMsg('核销失败');

        }

        $game_model = new CarGame();
        //清空当前使用卡
        $game_model->dataUpdate(['now_card_id'=>$input['card_id']],['now_card_id'=>'']);
        //判断类型 专业组还是普通
        $car_type_model = new CarType();

        $type = $car_type_model->getType($record['car_type_id'],$record['user_id']);

        $insert = [

            'uniacid'     => $this->_uniacid,

            'user_id'     => $record['user_id'],

            'record_id'   => $record['id'],

            'card_id'     => $input['card_id'],

            'now_card_id' => $input['card_id'],
            //比赛类型
            'major'       => $type,

            'car_type_id' => $record['car_type_id'],

            'atv_id'      => $record['atv_id'],
        ];
        //添加比赛记录标 准备开始比赛
        $res = $game_model->dataAdd($insert);

        if($res==0){

            Db::rollback();

            $this->errorMsg('核销失败');

        }
        //修改签到信息
        //查询是否正在排队
        $line_model = new CarLineUp();

        $dis = [

            'order_id' => $record['id'],

            'type'     => 2
        ];

        $line_model->dataUpdate($dis,['status'=>2]);
//        //如果有需要到账的积分
//        if(!empty($record['get_integral'])&&$record['have_tx']==0){
//
//            $integral_model = new \app\member\model\Integral();
//
//            $integral_model->integralUserAdd($record['user_id'],$record['get_integral'],$record['uniacid'],2,8,$record['id']);
//
//        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:54
     * @功能说明:用户地址列表
     */
    public function addressList(){

        $dis[] = ['user_id','=',$this->getUserId()];

        $dis[] = ['status','>',-1];

        $data = $this->address_model->dataList($dis,10);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:57
     * @功能说明:用户地址详情
     */
    public function addressInfo(){

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->address_model->dataInfo($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:58
     * @功能说明:添加用户地址
     */
    public function addressAdd(){

        $input = $this->_input;

        $input['uniacid'] = $this->_uniacid;

        $input['user_id'] = $this->getUserId();

        $res = $this->address_model->dataAdd($input);

        if($input['status']==1){

            $id = $this->address_model->getLastInsID();

            $this->address_model->updateOne($id);
        }

        return $this->success($res);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-19 15:58
     * @功能说明:添加用户地址
     */
    public function addressUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $res = $this->address_model->dataUpdate($dis,$input);

        if(!empty($input['status'])&&$input['status']==1){

            $this->address_model->updateOne($input['id']);

        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-11 22:54
     * @功能说明:获取默认地址
     */
    public function getDefultAddress(){

        $address_model = new Address();

//        dump(['user_id'=>$this->getUserId(),'status'=>1]);exit;

        $address = $address_model->dataInfo(['user_id'=>$this->getUserId(),'status'=>1]);

        return $this->success($address);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-19 16:13
     * @功能说明:删除地址
     */
    public function addressDel(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $res = $this->address_model->where($dis)->delete();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-22 13:56
     * @功能说明:修改用户信息 授权微信信息等
     */
    public function userUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $this->getUserId()
        ];

        if(!empty($input['coupon_atv_id'])&&empty($this->getUserInfo()['nickName'])&&!empty($input['nickName'])){

            $coupon_atv_model = new CouponAtv();

            $coupon_atv_model->invUser($this->getUserId(),$input['coupon_atv_id']);
        }

        if(isset($input['coupon_atv_id'])){

            unset($input['coupon_atv_id']);
        }

        if(isset($input['watermark'])){

            unset($input['watermark']);
        }

        $res = $this->model->dataUpdate($dis,$input);

        $user_info = $this->model->dataInfo(['id'=>$this->getUserId()]);

        setCache($this->autograph, $user_info, 7200, $this->_uniacid);

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-22 14:08
     * @功能说明:用户信息
     */
    public function userInfo(){

        $data = $this->getUserInfo();

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['status','in',[1,2,3,4]];

        $driver_model = new CarDriver();
        //查看是否是团长
        $cap_info = $driver_model->dataInfo($cap_dis);
        //-1表示未申请团长，1申请中，2已通过，3取消,4拒绝
        $data['driver_status'] = !empty($cap_info)?$cap_info['status']:-1;

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-23 09:39
     * @功能说明:团长详情
     */
    public function coachInfo(){

        $order_model = new Order();

        $order_model->coachBalanceArr($this->_uniacid);

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['status','in',[1,2,3,4]];

        $cap_info = $this->coach_model->dataInfo($cap_dis);


        return $this->success($cap_info);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-22 13:35
     * @功能说明:申请认证车手
     */
    public function carApply(){

        $input = $this->_input;

        $driver_model = new CarDriver();

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['status','>',-1];

        $cap_info = $driver_model->dataInfo($cap_dis);

        if(!empty($cap_info)&&in_array($cap_info['status'],[1,2,3])){

            $this->errorMsg('你已经申请过车手了了，');
        }

        $input['uniacid'] = $this->_uniacid;

        $input['user_id'] = $this->getUserId();

        $input['status']  = 1;


        if(!empty($cap_info)&&$cap_info['status']==4){

            $res = $driver_model->dataUpdate(['id'=>$cap_info['id']],$input);

        }else{

            $res = $driver_model->dataAdd($input);

        }

        return $this->success($res);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-26 10:43
     * @功能说明:车手详情
     */
    public function carInfo(){

        $driver_model = new CarDriver();

        $cap_dis[] = ['user_id','=',$this->getUserId()];

        $cap_dis[] = ['status','>',-1];

        $cap_info = $driver_model->dataInfo($cap_dis);

        return $this->success($cap_info);

    }





    /**
     * @author chenniang
     * @DataTime: 2021-07-08 11:51
     * @功能说明:用户优惠券列表
     */
    public function userCouponList(){

        $input = $this->_param;

        $this->coupon_record_model->initCoupon($this->_uniacid);

        $dis = [

            'user_id' => $this->getUserId(),

            'status'  => $input['status'],

            'is_show' => 1
        ];

        $data = $this->coupon_record_model->dataList($dis);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['start_time'] = date('Y.m.d H:i',$v['start_time']).' - '.date('Y.m.d H:i',$v['end_time']);

            }
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-16 22:09
     * @功能说明:删除优惠券
     */
    public function couponDel(){

        $input = $this->_input;

        $coupon = $this->coupon_record_model->dataInfo(['id'=>$input['coupon_id']]);

        if($coupon['status']==1){

            $this->errorMsg('待使用待卡券不能删除');
        }

        $res = $this->coupon_record_model->dataUpdate(['id'=>$input['coupon_id']],['is_show'=>0]);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-13 19:45
     * @功能说明:优惠券活动详情
     */
    public function couponAtvInfo(){

        $input = $this->_input;

        $atv_record_model = new CouponAtvRecord();

        $atv_record_list_model = new CouponAtvRecordList();

        $atv_model = new CouponAtv();

        if(empty($input['id'])){

            $dis_where[] = ['status','=',1];

            $dis_where[] = ['end_time','<',time()];
            //修改过期状态
            $atv_record_model->dataUpdate($dis_where,['status'=>3]);

            $dis = [

                'user_id' => $this->getUserId(),

                'status'  => 1
            ];
            //查询有没有进行中的活动
            $atv_ing = $atv_record_model->dataInfo($dis);

            if(empty($atv_ing)){

                $atv_ing = $this->couponAtvAdd();
            }
            //
            if(empty($atv_ing)){

                $atv_ing = $atv_record_model->where(['user_id'=>$this->getUserId()])->order('id desc')->find();

                $atv_ing = !empty($atv_ing)?$atv_ing->toArray():[];
            }

            if(empty($atv_ing)){

                $this->errorMsg('你没有可以进行的活动');
            }

        }else{

            $dis = [

                'id'  => $input['id']
            ];
            //查询有没有进行中的活动
            $atv_ing = $atv_record_model->dataInfo($dis);
        }

        $atv = $atv_model->dataInfo(['uniacid'=>$this->_uniacid]);

        $atv_ing['atv_num']   = $atv['atv_num'];

        $atv_ing['end_time'] -= time();

        $atv_ing['end_time']  = $atv_ing['end_time']>0?$atv_ing['end_time']:0;

        $data['atv_info']    = $atv_ing;
        //邀请记录
        $data['record_list'] = $atv_record_list_model->dataList(['a.record_id'=>$atv_ing['id']],50);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-12 16:29
     * @功能说明:发起优惠券活动
     */
    public function couponAtvAdd(){

        $atv_model  = new CouponAtv();

        $atv_record_model = new CouponAtvRecord();

        $atv_record_coupon_model = new CouponAtvRecordCoupon();

        $atv_config = $atv_model->dataInfo(['uniacid'=>$this->_uniacid]);


        if($atv_config['status']==0){

            return [];
        }

        if($atv_config['start_time']>time()||$atv_config['end_time']<time()){

            return [];

        }

        if(empty($atv_config['coupon'])){

            return [];

        }


        $where[] = ['user_id','=',$this->getUserId()];

        $where[] = ['status','<>',3];

        $count = $atv_record_model->where($where)->count();

        if($count>=$atv_config['atv_num']){

            return [];

        }

        $insert = [

            'uniacid' => $this->_uniacid,

            'user_id' => $this->getUserId(),

            'atv_id'  => $atv_config['id'],

            'atv_start_time' => $atv_config['start_time'],

            'atv_end_time'   => $atv_config['end_time'],

            'inv_user_num'   => $atv_config['inv_user_num'],

            'inv_time'     => $atv_config['inv_time'],

            'start_time'   => time(),

            'end_time'     => time()+$atv_config['inv_time']*3600,

            'inv_user'     => $atv_config['inv_user'],

            'to_inv_user'  => $atv_config['to_inv_user'],

            'share_img'    => $atv_config['share_img'],

         ];

        Db::startTrans();

         $res = $atv_record_model->dataAdd($insert);

         if($res==0){

             Db::rollback();

             $this->errorMsg('发起活动失败');
         }

         $record_id = $atv_record_model->getLastInsID();
         //记录该活动需要派发那些券
         foreach ($atv_config['coupon'] as $value){

             $insert = [

                 'uniacid'   => $this->_uniacid,

                 'atv_id'    => $atv_config['id'],

                 'record_id' => $record_id,

                 'coupon_id' => $value['coupon_id'],

                 'num'       => $value['num'],

             ];

             $res = $atv_record_coupon_model->dataAdd($insert);

             if($res==0){

                 Db::rollback();

                 $this->errorMsg('发起活动失败');
             }

         }

        Db::commit();

        $record = $atv_record_model->dataInfo(['id'=>$record_id]);

        return $record;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-25 17:40
     * @功能说明：生产二维码
     */

    public function atvQr(){

        $input = $this->_input;

        $key = 'atv_coupon'.$input['coupon_atv_id'];

        $qr  = getCache($key,$this->_uniacid);

        if(empty($qr)){

//            $qr_insert = [
//
//                'coupon_atv_id' => $input['coupon_atv_id']
//            ];
            //获取二维码
            $qr = $this->model->orderQr($input,$this->_uniacid);

            setCache($key,$qr,86400,$this->_uniacid);
        }

        return $this->success($qr);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-14 19:22
     * @功能说明:授权手机号
     */
    public function reportPhone ()
    {

        $params = $this->_input;

        $encryptedData = $params[ 'encryptedData' ];

        $iv            = $params[ 'iv' ];

        $config    = longbingGetAppConfig($this->_uniacid);

        $appid     = $config[ 'appid' ];

       // $appsecret = $config[ 'app_secret' ];

        $session_key = $this->model->where(['id'=>$this->getUserId()])->value('session_key');

        if(empty($session_key)){

            $this->errorMsg('need login',401);
        }
        $data = null;
        //  解密
        $errCode = decryptDataLongbing( $appid, $session_key, $encryptedData, $iv, $data );

        if ( $errCode == 0 )
        {
            $data = json_decode( $data, true );

            $phone = $data[ 'purePhoneNumber' ];

        }
        else
        {
            return $this->error( $errCode );
        }

        $res = $this->model->dataUpdate(['id'=>$this->getUserId()],['phone'=>$phone]);

        $user_info = $this->model->dataInfo(['id'=>$this->getUserId()]);

        setCache($this->autograph, $user_info, 7200, $this->_uniacid);

        return $this->success($phone);
    }




    /**
     * @author chenniang
     * @DataTime: 2021-09-29 10:16
     * @功能说明:查询有成绩对日期
     */
    public function resultDate(){

        $game_model = new CarGame();

        $dis = [

            'user_id' => $this->getUserId(),

            'have_game'  => 1
        ];

        $data = $game_model->where($dis)->order('id desc')->column('day');

        $data = array_values($data);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-29 10:29
     * @功能说明:根据日期获取比赛车型
     */
    public function resultCarType(){

        $params = $this->_param;

        $dis = [

            'user_id' => $this->getUserId(),

//            'status'  => 2,

            'day'     => $params['day']
        ];

        $game_model = new CarGame();

        $data = $game_model->where($dis)->order('id desc')->group('car_type_id')->field('car_type_id')->select()->toArray();

        if(!empty($data)){

            $car_type_model = new CarType();

            foreach ($data as &$v){

                $v['car_type_title'] = $car_type_model->where(['id'=>$v['car_type_id']])->value('title');

            }

        }


        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-29 10:33
     * @功能说明:个人成绩
     */
    public function userResult(){

        $params = $this->_param;

        $dis = [

            'user_id'     => $this->getUserId(),

            'car_type_id' => $params['car_type_id'],

        ];

        if(!empty($params['atv_id'])){

            $dis['atv_id'] = $params['atv_id'];
        }

        $game_model = new CarGame();
        //累计积分
        $data['integral'] = $this->record_model->where($dis)->whereTime('start_time',$params['day'])->sum('integral');

        $dis['day'] = $params['day'];
        //最快圈速
        $data['best_result'] = $game_model->where($dis)->min('best_time');

        $data['best_result'] = game_time($data['best_result']);
        //累计时长
        $data['total_time']  = $game_model->where($dis)->sum('total_time');

        $data['total_time']  = game_time($data['total_time']);
        //累计圈数
        $data['num']         = $game_model->where($dis)->sum('have_num');
        //用户类型 （1普通 2专业）
        $data['user_type']   = $game_model->where($dis)->value('major');

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-29 11:39
     * @功能说明:我的排队信息
     */

    public function myLineUp(){

        $params = $this->_param;

        $line_model = new CarLineUp();

        $dis = [

            'user_id'   => $this->getUserId(),

            'order_id'  => $params['order_id'],

            'type'      => $params['type'],

            'status'    => 0
        ];

        $data = $line_model->dataInfo($dis);

        if(empty($data)){

            $this->errorMsg('你暂无排队信息');
        }
        //排队号码
        $arr['code'] = $data['code'];

        $where[] = ['uniacid','=',$data['uniacid']];

        $where[] = ['status','=',0];

        $where[] = ['create_time','<',$data['create_time']];

        $where[] = ['id','<>',$data['id']];

        $count = $line_model->where($where)->count();
        //前面有多少人
        $arr['count'] = $count;

        $time = $line_model->where($where)->sum('number');

        $time = $time*120;
        //预计等待时间
        $arr['time'] = intval($time/60);

        return $this->success($arr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-29 13:22
     * @功能说明:签到
     */
    public function signUp(){

        $params = $this->_input;
        //查询是否正在排队
        $line_model = new CarLineUp();

        $order_model= $params['type']==1?new Order():$this->record_model;

        $order = $order_model->dataInfo(['id'=>$params['order_id']]);

        if($order['pay_type']!=2){

            $this->errorMsg('状态错误');
        }

        $refund_model = new RefundOrder();
        //判断有无申请中的退款订单
        $refund_order = $refund_model->dataInfo(['order_id'=>$order['id'],'status'=>1]);

        if(!empty($refund_order)){

            $this->errorMsg('该订单正在申请退款，请先处理');

        }

        Db::startTrans();

        $update = [

            'sign_time' => time(),

            'pay_type'  => 3
        ];

        $res = $order_model->dataUpdate(['id'=>$params['order_id']],$update);

        if($res==0){

            Db::rollback();

            $this->errorMsg('签到失败');
        }
        //排队号码
        $code = $line_model->where(['uniacid'=>$this->_uniacid])->max('code');

        $code++;
        //需要跑的圈数
        $number = $params['type']==1?$order['order_goods'][0]['circle']*$order['order_goods'][0]['num']:$order['number'];

        $insert = [

            'uniacid' => $this->_uniacid,

            'user_id' => $order['user_id'],

            'code'    => $code,

            'number'  => $number,

            'order_id'=> $order['id'],

            'type'    => $params['type']
        ];

        $res = $line_model->dataAdd($insert);

        if($res==0){

            Db::rollback();

            $this->errorMsg('签到失败');
        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-29 14:11
     * @功能说明:取消签到
     */
    public function cancelSignUp(){

        $params = $this->_input;
        //查询是否正在排队
        $line_model = new CarLineUp();

        $dis = [

            'order_id' => $params['order_id'],

            'type'     => $params['type']
        ];

        Db::startTrans();

        $line_model->dataUpdate($dis,['status'=>-1]);

        $order_model= $params['type']==1?new Order():$this->record_model;

        $update = [

            'sign_time' => 0,

            'pay_type'  => 2
        ];

        $res = $order_model->dataUpdate(['id'=>$params['order_id']],$update);

        if($res==0){

            Db::rollback();

            $this->errorMsg('签到失败');
        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-12 09:48
     * @功能说明:根据手机号获取银豹的会员列表
     */
    public function popalMemberByPhone(){

        $input = $this->_param;
        //先同步到本地
        $this->model->synMemberList($this->_uniacid);

        $member_model = new SynMember();

        if(empty($input['phone'])){

            $phone = $member_model->where(['user_id'=>$this->getUserId()])->value('phone');

        }else{

            $phone = $input['phone'];
        }

        $dis['phone'] = $phone;

        $data = $member_model->dataList($dis);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['is_select'] = $v['user_id']==$this->getUserId()?1:0;

            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-12 10:13
     * @功能说明:同步会员
     */
    public function bindMember(){

        $input = $this->_input;

        $user = $this->model->dataInfo(['id'=>$this->getUserId()]);

        $res  = $this->model->getMemberInfoOne($user,$input['uid']);

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-11-12 11:20
     * @功能说明:同步会员积分余额
     */
    public function synMemberCash(){

        $res = $this->model->synMemberCash($this->_uniacid,$this->getUserId());

        if(!empty($res['code'])){

            $this->errorMsg($res['msg']);
        }

        return $this->success($res);

    }












}
